<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/12/30
 * Time: 12:54
 */

namespace system\core\route;

/*
*请求接受类
*
*/
class Request
{

    ///单例
    protected static $instance;

    ///协议
    private $scheme = 'http';

    /// 主机地址
    private $host = "";

    /// 协议传输方式 GET POST
    private $method = "get";
    /// 端口
    private $port = 0;
    /// 请求路径
    private $path = "";
    /// 请求参数
    private $query = "";

    //请求参数数组
    private $input = array();

    private $url = "";

    private $root = '';

    /**
     * @return string
     */
    public function getRoot()
    {
        return $this->root;
    }




    ///构造函数，根据参数数量选择对应方法
    protected function __construct()
    {

        $this->setUrl();
        $this->setRoot();
        call_user_func(array($this,'parse_base_url'),$this->url);
    }


    
    /*
     * @param string $url url
     *
     * */
    private function parse_base_url($url)
    {
        $col = parse_url($url);

        !isset($col["scheme"]) && $col["scheme"] = "";
        !isset($col["host"]) && $col["host"] = "";
        !isset($col["path"]) && $col["path"] = "/";
        !isset($col["query"]) && $col["query"] = "";
        !isset($col["port"]) && $col["port"] = "";
        $this->scheme = $col["scheme"];
        $this->host = $col["host"];
        $this->port = !empty($col["port"]) ? $col["port"] : 80;
        $this->path = $col["path"];
        $this->setMethod();
        if(array_key_exists("query",$col))
        {
            $this->query = isset($col["query"])?$col["query"]:"";

        }
        $this->setInput();

    }

    /*
     * 把query转化为数组
     *
     * */
    private function setInput(){

        $this->input = $_REQUEST;

        /*if (!empty($this->query)){
            $inarr = explode('&', $this->query );
            foreach ($inarr as $k => $v){
                $in = explode('=',$v );
                $this->input[$in[0]] = $in[1];
            }
            
        }*/



    }

    /**
     * @param string $method
     */
    private function setMethod()
    {
        if (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST'))  {
            $this->method = 'POST'  ;
        }else{
            $this->method = 'GET'  ;
        }
    }

    

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return \system\core\route\Request
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    
    
    /*
     * 获得当前url
     *
     *
     * */
    private function setUrl($url=null){
        if (!empty($url)){
            $this->url = $url;
        }else{
            $current_url='http://';
            if(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'){
                $current_url='https://';
            }
            if($_SERVER['SERVER_PORT']!='80'){
                $current_url.=$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
            }else{
                $current_url.=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
            }

            $this->url = $current_url;

        }


    }


    /**
     * @param string $root
     */
    private function setRoot()
    {
        $current_url='http://';
        if(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'){
            $current_url='https://';
        }
        if($_SERVER['SERVER_PORT']!='80'){
            $current_url.=$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
        }else{
            $current_url.=$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'];
        }
        $this->root = dirname($current_url) ;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @return string
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return int
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * @return string
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * @return string
     */
    public function getScheme()
    {
        return $this->scheme;
    }





    /*
     * @return string clienip
     *
     * */

    public function getClienip()
    {
        //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
         
        $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        return $res;
    }



    /**
     * 是否为GET请求
     * @access public
     * @return bool
     */
    public function isGet()
    {
        return $this->getMethod() == 'GET';
    }

    /**
     * 是否为POST请求
     * @access public
     * @return bool
     */
    public function isPost()
    {
        return $this->getMethod() == 'POST';
    }


    /*
     * 参数数组
     * @param $ting $name 参数名字
     * @param $stirng method post 或者get
     *
     * */
    public function input($name = '',$method='all'){
        switch ($method){
            case 'all':{
                $in = $_REQUEST;
                break;
            }
            case 'get':{
                $in = $_GET;
                break;
            }
            case 'post':{
                $in = $_POST;
                break;
            }
            default:{
                $in = $_REQUEST;
            }
        }
        if (empty($name)){
            return $in;
        }else{
            if (empty($in[$name])){
                return $in;
            }else{
                return $in[$name];
            }


        }
    }

    

}